package net.pm.core.service.power.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.pm.common.dao.GenericDao;
import net.pm.common.service.impl.GenericServicerImpl;
import net.pm.common.toolkit.PMTool;
import net.pm.core.entities.db.DeptPower;
import net.pm.core.entities.db.Pmdept;
import net.pm.core.entities.db.Pmpower;
import net.pm.core.service.power.DeptPowerServicer;

import org.springframework.stereotype.Service;

@Service("DeptPowerServicer")
public class DeptPowerServicerImpl extends GenericServicerImpl<DeptPower, Long>
		implements DeptPowerServicer {

	@Resource(name = "DeptPowerDao")
	@Override
	public void setGenericDao(GenericDao<DeptPower, Long> genericDao) {
		super.genericDao = genericDao;
	}
	
	//改成用SQL...性能更佳
	@Override
	public List<String> findDeptPowerCodesByDeptId(Integer deptId) {
		final StringBuilder builder = new StringBuilder(
				"from DeptPower deptpower where deptpower.pmdept.id = ? ");
		List<DeptPower> deptpowers = super.findEntitiesByJpql(builder, deptId);
		List<String> powers = new ArrayList<String>(deptpowers.size());
		for (DeptPower deptpower : deptpowers) {
			powers.add(deptpower.getPmpower().getPowerCode());
		}
		return powers;
	}

	@Override
	public Long modifyDeptPower(Integer deptId, Integer[] powerIds) {
		if (!this.findDeptPowerCodesByDeptId(deptId).isEmpty())// 首先先清空,当前用户的权限
			this.removeDeptPower(deptId);
		// 进行更新
		List<DeptPower> deptpowers = new ArrayList<DeptPower>();
		// 是否选择中其的新权限
		if (PMTool.isNotEmpty(powerIds) && powerIds.length > 0) {
			for (Integer id : powerIds) {
				DeptPower deptpower = new DeptPower();
				deptpower.setPmdept(new Pmdept(deptId));
				deptpower.setPmpower(new Pmpower(id));
				deptpowers.add(deptpower);
			}
			super.batchCreate(deptpowers);
		}
		return DeptPowerServicer.power_modify_success;
	}

	@Override
	public Long removeDeptPower(Integer deptId) {
		final StringBuilder builder = new StringBuilder(
				" delete DeptPower deptpower where deptpower.pmdept.id =  ? ");
		if (super.removeByJpql(builder, deptId) > 0)
			return DeptPowerServicer.power_remove_success;
		return DeptPowerServicer.power_remove_failed;
	}

}
